import mongoose from 'mongoose';

export function connectToDatabase(): Promise<void> {
    const maxConnecting = Math.max(30, Number(process.env.DB_MAX_LINK || 20));
    return new Promise((resolve, reject) => {
        mongoose.connect(process.env.MONGO_URI!, {
            bufferCommands: true,
            maxConnecting: maxConnecting,
            maxPoolSize: maxConnecting,
            minPoolSize: 20,
            connectTimeoutMS: 60000,
            waitQueueTimeoutMS: 60000,
            socketTimeoutMS: 60000,
            maxIdleTimeMS: 300000,
            retryWrites: true,
            retryReads: true
        });
        const db = mongoose.connection;
        db.on('error', console.error.bind(console, 'MongoDB connection error:'));
        db.once('open', () => resolve());
    });
}
